package com.example.estest.config;

import com.example.estest.util.FileUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * Elasticsearch RestHighLevelClient配置
 */

@Configuration
public class ElasticsearchClientConfig {


    @Autowired
    private ElasticsearchClientBean properties;
    private RestHighLevelClient client;
    private RestClient restClient;

    @Value("${logpath}")
    private String logpath;

    @Bean("restHighLevelClient")
    public RestHighLevelClient getRestHighLevelClient() {
        HttpHost[] hosts = properties.getHosts().stream().map(h -> HttpHost.create(h)).toArray(HttpHost[]::new);

        // 基础身份验证
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));

        client = new RestHighLevelClient(
                RestClient.builder(hosts)
                        .setHttpClientConfigCallback(
                                httpClientBuilder ->
                                        httpClientBuilder.disableAuthCaching()
                                                .setDefaultCredentialsProvider(credentialsProvider)
                                                .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(8).build())
                        )
                        .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(900000)
                                .setSocketTimeout(900000).setConnectionRequestTimeout(900000)
                        )
        );
        System.out.println("Connecting Elasticsearch...");
        while (true) {
            try {
                if (client.ping(RequestOptions.DEFAULT)) {
                    break;
                }
            } catch (Exception e) {
                FileUtils.writeStringadd(logpath+"\\"+"error.log","Connecting Elasticsearch Failed, Retry in 10 seconds...");
                System.out.println("Connecting Elasticsearch Failed, Retry in 10 seconds...");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e1) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("Elasticsearch Connected!");
        return client;
    }

    public void close() {
        if(client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public RestClient getRestClient() {
        if (restClient == null && client != null){
            restClient = client.getLowLevelClient();
        }
        return restClient;
    }
}
